import { observable } from 'mobx'
import { getDefUserInfo } from "@path/api/user/defData"
import storage from '@/path/tool/storage'
import config from "@/path/service/config"
import { lock } from "@path/service/middleware/lockToken"
import { TypeUserStore } from "./type"
import { TypeMerchantWxLogin } from "@path/api/user/type"
import { merchantWxLogin, getUserByid, refreshToken } from "@/path/api/user";
import { Router } from '@/path/router'
import { XmDialogModal } from '@/components/public'
import Taro from '@tarojs/taro'
const storageName = "storageUserInfo"
export default observable<TypeUserStore>({
  userInfo: storage.getLocalStorage(storageName) || getDefUserInfo(),
  /**清空登录信息 */
  clearUserInfo() {
    this.setUserInfo(getDefUserInfo())
  },
  /**更新用户信息 */
  setUserInfo(user: TypeMerchantWxLogin.returnedVal) {
    this.userInfo = user
    lock.current.setValue(user.token)
    storage.setLocalStorageSync(storageName, user, config?.tokenCatcheTime)
  },
  /**
   * 微信登录
   * @param params 
   * @returns 
   */
  wxLogin(params: TypeMerchantWxLogin.parameter): Promise<TypeMerchantWxLogin.returnedVal> {
    return merchantWxLogin(params).then((res) => {
      this.setUserInfo(res.userinfo)
      this.refreshUserInfo()
      return this.userInfo
    })
  },
  /**刷新用户信息 */
  refreshUserInfo(token?: string): Promise<TypeMerchantWxLogin.returnedVal> {
    return new Promise((resolve, reject) => {

      if (!this.userInfo?.token) {
        setTimeout(() => {
          reject()
        }, 100);
        return
      }
      getUserByid(token).then((res) => {
        if (res.data == null) return reject()
        const _data = { ...this.userInfo, ...(res.data.userinfo || {}) }
        this.setUserInfo(_data)
        Taro.eventCenter.trigger("userinfoGeted", _data)
        resolve(_data)
      }).catch((err) => {
        if (err.code === 20002) {
          this.logout()
        }
        reject()
      })
    })
  },
  /**刷新token信息 */
  refreshToken() {
    return new Promise((resolve, reject) => {
      if (!this.userInfo?.token) {
        Router.toUserLogin().then((user) => {
          if (user?.token) return resolve(user)
          reject()
        }).catch(() => {
          reject()
        })
        return
      }
      refreshToken().then((res) => {
        return this.refreshUserInfo(res.data.token)
      }).then((res) => {
        this.setUserInfo(res.data)
        resolve(res.data)
      }).catch(() => {
        XmDialogModal({
          title: "提示",
          content: "会话已过期，请重新登录!!"
        }).then(() => {
          return Router.toUserLogin()
        }).then((user) => {
          if (user?.token) return resolve(user)
          reject()
        }).catch(() => {
          reject()
        })
      })
    })
  },
  /**登出 */
  logout() {
    return new Promise((resolve) => {
      this.clearUserInfo()
      Router.toTabbarIndex()
      resolve(true)
    })
  },
})
